const app = getApp()
import {
  getAddressList,
  add,
  del,
  choose,
} from '../../api/address'
let loading = false
Page({
  data: {
    activeId: null,
    info: null,
    addressList: [

    ],
    editVisible: !true,
    id: null,
    newAddressId: null,

  },
  onLoad(options) {
    if (options.id) {
      this.setData({
        id: options.id,
      })
    }
  },
  onShow() {
    this.getList();
  },
  onClickLeft() {
    // wx.showToast({
    //   title: '点击返回',
    //   icon: 'none'
    // });
    wx.navigateBack({
      delta: 1,
    })
  },
  showEdit() {
    console.log(1)
    this.setData({
      editVisible: true,
      activeId: null,
    })
  },
  closeEdit() {
    this.setData({
      editVisible: false,
      activeId: null,
    })
  },
  addAddressByWeChat() {
    wx.chooseAddress({
      success: (res) => {
        console.log(res.userName)
        console.log(res.postalCode)
        console.log(res.provinceName)
        console.log(res.cityName)
        console.log(res.countyName)
        console.log(res.detailInfo)
        console.log(res.nationalCode)
        console.log(res.telNumber)
        const params = {
          post_receiver: res.userName,
          post_phone: res.telNumber,
          post_address: res.detailInfo,
          post_city: res.cityName,
          post_province: res.provinceName,
          post_district: res.countyName,
          // receiverId: res.receiverId
        }
        add(params).then(res => {

            console.log(res)
            if (res.data.receiverId) {
              this.setNewAddressId({
                detail: res.data.receiverId
              })
            }
            wx.showToast({
              title: '新增地址成功',
              icon: 'none'
            })
            this.getList();
          })
          .catch(err => {
            wx.showToast({
              title: '新增地址失败',
              icon: 'none'
            })
          })
      }
    })
  },
  setNewAddressId(e) {
    const newAddressId = e.detail
    this.setData({
      newAddressId,
    })
  },
  del(e) {
    const {
      id
    } = e.currentTarget.dataset
    console.log(id)
    wx.showModal({
      title: '提示',
      content: '确定删除吗',
      success: (res) => {
        if (res.confirm) {
          del({
              id,
            })
            .then(res => {
              wx.showToast({
                title: '删除成功',
                icon: 'none'
              })
              this.getList();
            })
            .catch(err => {
              wx.showToast({
                title: '删除失败',
                icon: 'none'
              })
            })


        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  edit(e) {
    const {
      id
    } = e.currentTarget.dataset
    const info = this.data.addressList.find(item => item.receiverId === id)
    console.log(id,info)
    this.setData({
      activeId: id,

      info: {
  
        // detail: info.address,
        // location: info.location,
        post_receiver: info.postReceiver,
        post_phone: info.postPhone,
        post_address: info.postAddress,
        post_city: info.postCity,
        post_province: info.postProvince,
        post_district: info.postDistrict,
        receiver_id: info.receiverId

      },
      editVisible: true,
    })

  },
  getList() {
    const params = {
      editVisible: false,
      activeId: null,

    }

    this.setData({
      ...params
    })
    getAddressList({}).then(res => {
        console.log(res)
        let list = res.data.list
        list = list.map(item => {
          const {postProvince, postCity, postDistrict ,postAddress} = item 
          item.location = `${postProvince}${postCity}${postDistrict}`
          item.address = ` ${postAddress}`
          return {
            ...item,
            detail: `${item.location} ${item.address}`,
            name: item.user_name,
            id: item.address_id
          }
        })
        if (list) {
          this.setData({
            addressList: list
          })
          this.askNewAddressId()
        }
      })
      .catch(err => {
        console.log(err)
      })
  },
  getNewList(e){
    console.log(e)
    if(e&&e.detail){
      this.setData({
        newAddressId: e.detail
      })
      this.getList()
    }
    else{
      this.setData({
        editVisible: false,
        activeId: null
      })
      this.getList()
    }
  },
  chooseDefaultId(id) {
    choose({
        id,
      })
      .then(res => {
        this.setData({
          id,
        })
        
        const eventChannel = this.getOpenerEventChannel();
        let item = this.data.addressList.find( (x) => {
          return x.receiverId === id
        })
        const { detail ,postReceiver , postPhone} = item
        eventChannel.emit('setReceiverId', {
          receiverId: id,
          name: postReceiver,
          phone: postPhone,
          address: detail,
        });
        wx.showToast({
          title: '选中成功 1s后返回上一页',
          icon: 'none'
        })
        setTimeout(()=> {
          wx.navigateBack({
            delta:1
          })
        }, 1200)
        // setTimeout(() => {
          this.getList();
        // }, 1000)
      })
      .catch(err => {
        wx.showToast({
          title: '选中失败',
          icon: 'none'
        })
      })
  },
  select(e) {
    const {
      id
    } = e.currentTarget.dataset
    console.log(id)
    wx.showModal({
      title: '提示',
      content: '确定选中当前地址吗',
      success: (res) => {
        if (res.confirm) {

          this.chooseDefaultId(id)

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  askNewAddressId() {
    console.log(loading, this.data.newAddressId)
    if(!newAddressId){
      return 
    }
    if (loading) {
      return
    }
    loading = true;
    const {
      newAddressId
    } = this.data
    if (newAddressId === null||this.askNewAddressId =='') {
      loading = false;

      return;
    }
    wx.showModal({
      title: '提示',
      content: '是否选中新添加的地址为默认地址',
      success: (res) => {
        loading = false;
        if (res.confirm) {
          this.setData({
            newAddressId: null,
          })
          this.chooseDefaultId(newAddressId)

        } else if (res.cancel) {
          console.log('用户点击取消')
          this.setData({
            newAddressId: null,
          })
        }
      }
    })
  }
})